// pages/product/index.js

/*************************************
 * 定时锁定，触发时后台发送锁定指令 
 ************************************ */
import { operationCode } from "../../utils/config"
const {dateTimeData} = require('../../utils/dateTimer');
const { Web_Socket } = require('../../utils/socket');
const { bytes2long, fnamefixed, long2Bytes, Uint8Array2HexStr } = require('../../utils/util');

const code = operationCode
let alreadySchedule = 0, scheduleSuccessed = 0, scheduleCancel = 0;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        countS: 0,//定时数量
        active: false,
        buttons: [{ type: 'default', text: '取消', className: 'dialogCancel' }, {type: 'primary',  text: '确定', className: 'dialogConfirm' }],
    },

    async postOthers(message) {
        const {deviceKey, kvMap} = message;
        Object.keys(kvMap).forEach(i => console.log(`schedule页面 ${deviceKey}=>请求`, `指令Hex[${parseInt(i).toString(16).toUpperCase().padStart(4, '0')}]`, `值Hex[${Uint8Array2HexStr(kvMap[i], ',')}]`))
        await wx.$http.post({url: '/szm/netty/postOthers', data: message})
        this.setData({showLoading: 1})
    },

    tapShowHalt: function() {
        const {endIndex} = this.data;
        this.setData({
            showHalf: true,
            endIndex: endIndex
        });
    },
    
    switchChange: function(e) {
        const active = e.detail.value ? 1 : 0;
        scheduleCancel = 0;
        scheduleSuccessed = 0;
        this.setData({
            operationSwitch: active,
            active: !active,
        })
        const {new_selectedTime} = this.data;
        if(active && !new_selectedTime) {
            wx.showToast({
              title: '请选择锁定时间',
              icon: 'none'
            })
            return;
        }

        const value = active ? [active, ...long2Bytes(new Date(new_selectedTime).getTime())] : [active, 0, 0, 0, 0, 0, 0, 0, 0]

        this.deviceKeys.forEach(k => {
            const message = {
                deviceKey: k,
                kvMap: {
                    [code.scheduleLocking]: value,
                    [code.token]: 'token123'
                }
            }
            this.postOthers(message);
        })
    },

    /**过期 */
    switchChange222: function(e) {
        const active = e.detail.value ? 1 : 0;
        this.setData({active: !active})
        const {scheduleJobId, selectedTime} = this.data;
        if(!selectedTime) {
            wx.showToast({
              title: '请选择锁定时间',
              icon: 'none'
            })
            return;
        }
        
        const sd = new Date(selectedTime);
        const payload = {
            beanName: "lockingTask",
            cronExpression: [sd.getFullYear(), '?', sd.getMonth() + 1, sd.getDate(), sd.getHours(), sd.getMinutes(), '0'].reverse().join(' '),
            params: wx.getStorageSync('deviceKey'),
            remark: "定时锁定",
            status:  1
        }

        if (active) {
            if (scheduleJobId) {
                if (this.data.cronExpression === payload.cronExpression) {//恢复
                    wx.$http.put({url: '/job/schedule/resume', data: [scheduleJobId]}).then(res => {
                        this.setData({active: 1})
                        wx.showToast({
                          title: '恢复定时',
                        })
                    })
                } else {//修改
                    payload.id = scheduleJobId;
                    wx.$http.put({url: '/job/schedule', data: payload}).then(res => {
                        this.setData({active: 1})
                        wx.showToast({
                          title: '修改定时',
                        })
                    })
                }
            } else {//新增
                wx.$http.post({url: '/job/schedule', data: payload}).then(res => {
                    this.setData({active: 1})
                    if (res.code === 0 && res.data) {
                        this.setData({scheduleJobId: res.data.id})
                    }
                    wx.showToast({
                      title: '开启定时',
                    })
                })
            }
        } else {
            if (scheduleJobId) {//暂停
                wx.$http.put({url: '/job/schedule/pause', data: [scheduleJobId]}).then(res => {
                    this.setData({active: 0})
                    wx.showToast({
                      title: '暂停定时',
                    })
                })
            } else {//取消
                wx.$http.delete({url: '/job/schedule', data: [scheduleJobId]}).then(res => {
                    this.setData({active: 0})
                    wx.showToast({
                      title: '取消定时',
                    })
                })
            }
         }
    },
    
    /**关闭半屏弹窗回调 */
    tapHalfButton: function(e) {
        const {endArray, endIndex, selectedTime} = this.data;
        this.setData({showHalf: false})
        const date = [endArray[0][endIndex[0]], endArray[1][endIndex[1]], endArray[2][endIndex[2]]].join('-');
        const time = [endArray[3][endIndex[3]], endArray[4][endIndex[4]]].join(':');
        const new_selectedTime = [date, time].join(' ');
        if (new_selectedTime && selectedTime !== new_selectedTime) {
            this.setData({active: !1})
        }
        this.setData({new_selectedTime})
    },

    initData() {
        const d = dateTimeData(new Date(Date.now() + 3600000))
        this.setData({
            endArray: d.dateTimeArray,
            endIndex: d.dateTime.slice(0,5)
        })
    },

    /**选中日期 */
    changeEndTime: function(e) {
        this.setData({
            endIndex: e.detail.value
        });
    },

    [fnamefixed(code.scheduleLocking)](data, deviceKey) {
        // this.deviceObj[deviceKey][1] = data[0];
        // const countS_new = Object.values(this.deviceObj).reduce((acc, cur) => acc + cur[1], 0);
        if (data[0]) {
            const {operationSwitch} = this.data;
            if(operationSwitch) {
                scheduleSuccessed++;
                wx.showToast({
                  title: `开启定时${scheduleSuccessed}`,
                })
                if (this.countEdun === scheduleSuccessed) {
                    this.setData({active: 1})
                }
            } else {
                scheduleCancel++
                wx.showToast({
                    title: `取消定时${scheduleCancel}`,
                  })
                  if (this.countEdun === scheduleCancel) {
                      this.setData({active: !1})
                  }
            }
        }
    },

    [fnamefixed(code.scheduleTime)](data, deviceKey) {
        if (data[0] === 1) {
            const selectedTime = new Date(Number(bytes2long(data.slice(1, 9)))).Format('yyyy-MM-dd HH:mm:ss')
            // this.deviceObj[deviceKey][0] = data[0];
            // const countS = Object.values(this.deviceObj).reduce((acc, cur) => acc + cur[0], 0);
            alreadySchedule++;
            wx.showToast({
              title: '定时中' + alreadySchedule,
            })
            this.setData({
                countS,
                active: this.countEdun === alreadySchedule,
                selectedTime,
                new_selectedTime: selectedTime
            });
        }
    },

    socketOnMessage() {
        wx.$eventEmitter.off('schedule');
        wx.$eventEmitter.on('schedule', (data) => {
            this.setData({showLoading: false})
            const { kvMap, deviceKey } = data;
            Object.keys(kvMap).forEach(k => {
                const bCode = parseInt(k);
                const fname = fnamefixed(bCode);
                this[fname] && this[fname](kvMap[bCode], deviceKey)
            });
        });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.socketOnMessage();

        const {id} = options;
        this.setData({deviceId: id})
        this.initData();

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        
    },

    /**CgAIS0g5V2J0dDAACgEB
     * 生命周期函数--监听页面显示
     */
    onShow() {
        alreadySchedule = 0;
        this.setData({subTitle: ""})
        Web_Socket.buildSocket('schedule');
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on("deviceKeys", ({keys, countEdun}) => {
            this.countEdun = countEdun;
            this.deviceKeys = keys;
            this.deviceObj = keys.reduce((acc, cur) => Object.assign(acc, {[cur]: [0, 0]}), {});
            this.setData({subTitle: keys.length > 1 ? "全部" : ""})
            console.log(this.deviceKeys)
            this.deviceKeys.forEach(k => {
                const message = {
                    deviceKey: k,
                    kvMap: {
                        [code.scheduleTime]: [1],
                        [code.token]: 'token123'
                    }
                }
                this.postOthers(message);
            })
        })

        

        // wx.$http.get({url: `/job/schedule/param/${wx.getStorageSync('deviceKey')}`}).then(res => {
        //     if (res.data) {
        //         const {id, cronExpression, status} = res.data;
        //         const ta = cronExpression.split(" ");
        //         this.setData({
        //             scheduleJobId: id, 
        //             cronExpression: cronExpression,
        //             selectedTime: [ta[6], ta[4], ta[3]].join('-') + ' ' + [ta[2], ta[1]].join(':'),
        //             status,
        //             active: status
        //         });
        //     }
        // });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})